package com.caszx.chargingpile.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONException;
import com.app.base.app.BaseTopBarDelayActivity;
import com.app.utils.DiskUser;
import com.app.utils.MD5;
import com.app.utils.RegularHelper;
import com.app.utils.SystemHelper;
import com.caszx.chargingpile.R;
import com.caszx.chargingpile.eventbus.EventBusAction;
import com.caszx.chargingpile.http.ConstantUrl;
import com.caszx.chargingpile.utils.DialogHelp;
import com.caszx.chargingpile.utils.SnackbarHelp;

import org.json.JSONObject;

import java.util.HashMap;

import de.greenrobot.event.EventBus;
import http.okhttp.OkHttpUtils;
import http.okhttp.callback.JsonCallback;
import okhttp3.Call;

/**
 *
 *登录
 * */
public class UserSignInActivity extends BaseTopBarDelayActivity implements View.OnClickListener {

    private final  static int REQUESTCODE = 100;
    private EditText edit_phone;
    private EditText edit_passwd;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_sign_in);
        setCenterTitle(R.string.string_sign_in);
    }

    @Override
    protected void findView() {
        edit_phone = (EditText) findViewById(R.id.edit_phone);
        edit_passwd = (EditText) findViewById(R.id.edit_passwd);
        findViewById(R.id.btn_signin).setOnClickListener(this);
        signUp();
        forgetPasswd();
    }

    private void forgetPasswd(){
        TextView btn_forget_passwd = (TextView) findViewById(R.id.btn_forget_passwd);
        btn_forget_passwd.setMovementMethod(LinkMovementMethod.getInstance());
        SpannableStringBuilder builder = new SpannableStringBuilder("忘记密码?");
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(false);
            }
            @Override
            public void onClick(View widget) {
                Intent intent = new Intent(UserSignInActivity.this,UserSignUpPassWdActivity.class);
                intent.putExtra("TYPE",UserSignUpPassWdActivity.USER_MD_PASSWD);
                startActivity(intent);
            }
        };
        builder.setSpan(clickableSpan, 0, builder.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        btn_forget_passwd.setText(builder);
    }

    private void signUp(){
        TextView btn_sign_up = (TextView) findViewById(R.id.btn_sign_up);
        btn_sign_up.setMovementMethod(LinkMovementMethod.getInstance());
        SpannableStringBuilder builder = new SpannableStringBuilder("注册");
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(false);
            }
            @Override
            public void onClick(View widget) {
                Intent intent = new Intent(UserSignInActivity.this,UserSignUpPassWdActivity.class);
                intent.putExtra("TYPE",UserSignUpPassWdActivity.USER_SIGN_UP);
                startActivityForResult(intent,REQUESTCODE);

            }
        };
        builder.setSpan(clickableSpan, 0, builder.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        btn_sign_up.setText(builder);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_signin:
                SystemHelper.closeInputFromWindow(this);
                String phone =edit_phone.getText().toString().trim();
                String passwd =edit_passwd.getText().toString().trim();
                if(!RegularHelper.isMobileNO(phone)){
                    SnackbarHelp.showSnackbarMsg(UserSignInActivity.this,"请输入正确的手机号");
                    return;
                }
                if(TextUtils.isEmpty(passwd)){
                    SnackbarHelp.showSnackbarMsg(UserSignInActivity.this,"请输入密码");
                    return;
                }
                signIn(phone,passwd);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(REQUESTCODE == requestCode&& UserSignUpPassWdActivity.SIGN_IN_RESULT_CODE == resultCode&&data!=null){
            //注册成功
            String phone = data.getStringExtra("PHONE");
            String paw = data.getStringExtra("PAW");
            signIn(phone,paw);
        }
    }

    /**
     * 登录
     * */
    private void signIn(String phone,String passwd){
        showProgressDialog("登录");
        HashMap<String,String> params = new HashMap<>();
        params.put("phone",phone);
        params.put("pwd", passwd);
        OkHttpUtils.post()
                .url(ConstantUrl.URL_SIGIN_IN)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        dissmissProgressDialog();
                        SnackbarHelp.showSnackbarMsg(UserSignInActivity.this,getResources().getString(R.string.error_network));
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        dissmissProgressDialog();
                        JSONObject resultJsonObject =  response.optJSONObject("result");
                        if(resultJsonObject!=null){
                            int code =  resultJsonObject.optInt("code");
                            if(code<0){
                                //error
                                 DialogHelp.showDialogOnlyMesg(UserSignInActivity.this,resultJsonObject.optString("msg"),null);
                            }else{
                                try {
                                    //成功
                                    String token = response.optString("token");
                                    String acount = response.optString("acount");
                                    DiskUser.saveValueByKey(UserSignInActivity.this,"token",token);
                                    DiskUser.saveValueByKey(UserSignInActivity.this,"acount",acount);
                                    EventBus.getDefault().post(EventBusAction.ACTION_SING_IN);
                                    finish();
                                }catch (JSONException e){
                                    SnackbarHelp. showSnackbarMsg(UserSignInActivity.this,getResources().getString(R.string.error_parser_json));
                                }
                            }
                        }
                    }
                });

    }


}
